<script setup>
import { ref, watch } from 'vue'
import { getSubcategories } from '../api/book'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue'])

const level1Options = ref([])
const level2Options = ref([])
const level3Options = ref([])

const selected = ref({
  level1: '',
  level2: '',
  level3: ''
})

// 先定义 emitSelection 函数
const emitSelection = () => {
  emit('update:modelValue', { ...selected.value })
}

// 初始化时加载一级分类
const loadLevel1 = async () => {
  try {
    const res = await getSubcategories({ level: '1' })
    level1Options.value = res.data
  } catch (error) {
    console.error('加载一级分类失败:', error)
  }
}

// 加载二级分类
const loadLevel2 = async () => {
  if (!selected.value.level1) {
    level2Options.value = []
    selected.value.level2 = ''
    return
  }
  
  try {
    const res = await getSubcategories({ 
      level: '2', 
      parent: selected.value.level1 
    })
    level2Options.value = res.data
  } catch (error) {
    console.error('加载二级分类失败:', error)
  }
}

// 加载三级分类
const loadLevel3 = async () => {
  if (!selected.value.level2) {
    level3Options.value = []
    selected.value.level3 = ''
    return
  }
  
  try {
    const res = await getSubcategories({ 
      level: '3', 
      parent: selected.value.level2 
    })
    level3Options.value = res.data
  } catch (error) {
    console.error('加载三级分类失败:', error)
  }
}

// 监听选择变化
watch(() => selected.value.level1, (newVal) => {
  selected.value.level2 = ''
  selected.value.level3 = ''
  loadLevel2()
  emitSelection()  // 现在可以安全调用
})

watch(() => selected.value.level2, (newVal) => {
  selected.value.level3 = ''
  loadLevel3()
  emitSelection()  // 现在可以安全调用
})

watch(() => selected.value.level3, emitSelection)  // 现在可以安全调用

// 初始化
loadLevel1()
</script>

<template>
  <div class="category-tree">
    <el-select 
      v-model="selected.level1" 
      placeholder="一级分类" 
      clearable
      style="width: 150px; margin-right: 10px;"
    >
      <el-option
        v-for="item in level1Options"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>

    <el-select 
      v-model="selected.level2" 
      placeholder="二级分类" 
      clearable
      :disabled="!selected.level1"
      style="width: 150px; margin-right: 10px;"
    >
      <el-option
        v-for="item in level2Options"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>

    <el-select 
      v-model="selected.level3" 
      placeholder="三级分类" 
      clearable
      :disabled="!selected.level2"
      style="width: 150px;"
    >
      <el-option
        v-for="item in level3Options"
        :key="item"
        :label="item"
        :value="item"
      />
    </el-select>
  </div>
</template>

<style scoped>
.category-tree {
  display: flex;
  margin-bottom: 20px;
}
</style>